import { createRouter, createWebHistory } from 'vue-router'
import { defineAsyncComponent } from 'vue'
import { useUserStore } from '@/store/modules/user/user.js'
import BaseLoading from '../components/loading/BaseLoading.vue'
import ErrorComponent from '../components/loading/ErrorComponent.vue'

const loadAsyncComponent = (componentPath) => {
  return defineAsyncComponent({
    // 添加延迟
    loader: () => import(`../views/${componentPath}`), // 动态导入页面组件
    loadingComponent: BaseLoading, // 加载时显示的动画组件
    delay: 200, // 延迟200ms显示加载动画（避免快速加载时闪烁）
    timeout: 5000, // 5秒内未加载完成则视为失败
    errorComponent: ErrorComponent, // 加载失败时显示的组件
  });
}


const routes = [
  { path: '/home', component: loadAsyncComponent('home/Home.vue'), alias: '/' },
  { path: '/message', component: loadAsyncComponent('message/Message.vue')
    
   },
  { path: '/video', component: loadAsyncComponent('video/Video.vue') },
  { path: '/user', component: loadAsyncComponent('user/User.vue') },
  { path: '/follow', component: loadAsyncComponent('follow/Follow.vue') }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const whiteList = ['/home', '/']

router.beforeEach(async (to, from, next) => {
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  const userStore = useUserStore()
  const isLogin = await userStore.checkLogin()
  if (isLogin) {
    next()
  } else {
    userStore.showLogin()
    next(false)
  }
})

export default router